package com.changgou.page.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.CategoryFeign;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Category;
import com.changgou.goods.pojo.Goods;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.page.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-22 21:17
 */
@Service
public class PageServiceImpl implements PageService {


    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private CategoryFeign categoryFeign;

    @Value("${pagePath}")
    private String pagePath;

    /**
     * 生成静态页面
     * @param spuId
     */
    @Override
    public void generateItemPage(String spuId) {
        Context context = new Context();
        Map<String,Object> map = new HashMap();
        Goods goods = spuFeign.findGoodsById(spuId).getData();
        Spu spu = goods.getSpu();
        List<Sku> skuList = goods.getSkuList();
        Category category1 = categoryFeign.findById(spu.getCategory1Id()).getData();
        Category category2 = categoryFeign.findById(spu.getCategory2Id()).getData();
        Category category3 = categoryFeign.findById(spu.getCategory3Id()).getData();

        map.put("spu",spu);
        map.put("category1",category1);
        map.put("category2",category2);
        map.put("category3",category3);
        map.put("spuImages",spu.getImage().split(","));

        map.put("specList", JSON.parseObject(spu.getSpecItems(),Map.class));
        for (Sku sku : skuList) {
            map.put("sku",sku);
            map.put("specList",JSON.parseObject(sku.getSpec(),Map.class));
            map.put("skuImages",sku.getImage().split(","));
            context.setVariables(map);

            File dest = new File(pagePath);
            if (!dest.exists()){
                //如果文件路径不存在 则创建该文件路径
                dest.mkdirs();
            }

            File file = new File(dest + sku.getId() + ".html");

            PrintWriter out = null;
            try {
                out = new PrintWriter(file,"UTF-8");
                templateEngine.process("item",context,out);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    out.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
